package rest

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"gitee.com/go-course/go9/tree/master/projects/vblog/api/apps/user"
	"github.com/infraboard/mcube/client/rest"
)

// CreateBlog   sdk ---> restfulAPI

func NewClient(conf *Config) *Client {
	c := rest.NewRESTClient()
	c.SetBaseURL(conf.URL)
	c.SetBasicAuth(conf.Username, conf.Password)
	return &Client{c: c, conf: conf}
}

type Client struct {
	conf *Config
	c    *rest.RESTClient

	session *user.Session
}

func (c *Client) Session() string {
	return fmt.Sprintf("username: %s, session: %s",
		c.session.UserName,
		c.session.Id)
}

func (c *Client) Login() error {
	// http://127.0.0.1:8050/vblog/api/v1/user/login
	// {
	// 	"code": 200,
	// 	"message": {
	// 		"username": "admin",
	// 		"session": "ce0uhc93n7pkm77le9l0"
	// 	}
	// }
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	resp := &Response{Message: &user.Session{}}

	err := c.c.Post("user/login").Do(ctx).Into(resp)
	if err != nil {
		return err
	}

	c.session = resp.Message

	// 给Restful Client 设置Session
	c.c.SetCookie(&http.Cookie{
		Name:  "username",
		Value: c.session.UserName,
	}, &http.Cookie{
		Name:  "session",
		Value: c.session.Id,
	})
	return nil
}

type Response struct {
	Code    int           `json:"code"`
	Message *user.Session `json:"message"`
}
